#include <IDTKTON.h>

char CalcDigit1( const char *code )
{
	char	aux[19];
	int	len;
	int	i;
	int	odd=0;
	int	even=0;
	char	dv;

	memset( aux, 0, sizeof(aux) );

	len = strlen( code );

	if ( (len % 2) == 0 )
	{
		aux[0] = '0';
		strcpy( aux+1, code );
		len += 1;
	}
	else
		strcpy( aux, code );

	for ( i=0; aux[i] && i<len; i+=2 )
		even += (int) (aux[i] - '0');

	for ( i=1; aux[i] && i<len; i+=2 )
		odd += (int) (aux[i] - '0');

	dv = ( ( ( even * 3 ) + odd ) % 10 ) + '0';

	return dv;
}

char CalcDigit2( const char* code )
{
	char	aux[19];
	int	i;
	int	odd=0;
	int	even=0;
	char	dv;

	memset( aux, 0, sizeof( aux ) );

	strcpy( aux, code );

	for ( i=1; i<16; i+=2 )
		even += (int) aux[i] - '0';

	for ( i=0; i<17; i+=2 )
		odd += (int) aux[i] - '0';

	dv = ( ( ( even * 3 ) + odd ) % 10 ) + '0';

	return dv;
}

//idTrans[19]  ( idOnline + dv1 + dv2 )
//idTicketOn[19]
//mode 1->convertir idTrans en idTicket -  0->convertir idTicket en idTrans

void getIdTicket( char *idTrans, char *idTicketOn, unsigned char mode )
{
	char	dv;
	int	i, j;
	char	aux[19];

	unsigned char mapa[10][17]={ {1, 3, 4, 5, 6, 9, 0, 14, 11, 13, 15, 2, 7, 8, 10, 12, 16},
										{16, 12, 10, 8, 7, 2, 15, 13, 11, 14, 0, 9, 6, 5, 4, 3, 1},
										{2, 4, 6, 8, 7, 9, 16, 13, 11, 0, 14, 5, 12, 10, 3, 1, 15},
										{15, 1, 3, 10, 12, 5, 14, 0, 11, 13, 16, 9, 7, 8, 6, 4, 2},
										{3, 6, 9, 11, 14, 2, 4, 8, 10, 12, 16, 1, 7, 13, 15, 5, 0},
										{0, 5, 15, 13, 7, 1, 16, 12, 10, 8, 4, 2, 14, 11, 9, 6, 3},
										{4, 8, 12, 16, 2, 6, 10, 14, 3, 9, 11, 15, 0, 1, 5, 7, 13},
										{13, 7, 5, 1, 0, 15, 11, 9, 3, 14, 10, 6, 2, 16, 12, 8, 4},
										{5, 10, 15, 2, 4, 8, 12, 14, 16, 3, 6, 9, 1, 0, 7, 11, 13},
										{13, 11, 7, 0, 1, 9, 6, 3, 16, 14, 12, 8, 4, 2, 15, 10, 5},
										};


	if ( mode == 1 )
	{
		memset( aux, 0, sizeof( aux ) );
		memset( idTicketOn, 0, 18 );
		memcpy( aux, idTrans+3, 15 );
		aux[15] = '1';
		dv = CalcDigit1( (const char*) aux );
		aux[16] = dv;
		dv = CalcDigit2( (const char*) aux );
		idTicketOn[17] = dv;

		for ( i=0; i<17; i++)
			idTicketOn[i] = aux[mapa[dv-'0'][i]];
	}
	else
	{
		memset( aux, 0, sizeof( aux ) );
		dv = idTicketOn[17];

		for ( i=0; i<17; i++ )
		{
			for ( j=0; j<17; j++ )
			{
				if ( mapa[dv-'0'][j] == i )
				{
					aux[i] = idTicketOn[j];
					break;
				}
			}
		}

		strncpy( idTrans, aux+1, 14 )[14] = 0;
	}
}
